#!coding=utf-8
from django.shortcuts import *
from models import *
from django.views.decorators.csrf import csrf_exempt
import simplejson
from util.form_util  import *
from django.http import HttpResponseRedirect
import json
@csrf_exempt
def editFillPeople(request):
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    basic=None
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
    if request.method == "GET":
        if appModel:
            appModel=appModel[0]
            basic_list = Fillpeopleinfo.objects.filter(enterprise = _enterPrise,application_status=appModel)
        if len(basic_list) > 0:
            basic = basic_list[0]
        return render_to_response('enterprise/basic_information/info/basic_info_fill_PeopleEdit.html', {  'basic' : basic } ,context_instance=RequestContext(request))
    if request.method == "POST":
        Fillpeopleinfo.objects.filter(enterprise = _enterPrise,application_status=appModel).delete()
        try:
            key= request.GET['key']
            basic_list=Fillpeopleinfo.objects.filter(enterprise = _enterPrise,submit_type='2',application_status=appModel)
            if basic_list:
                basic = basic_list[0]
            else:
                basic = Fillpeopleinfo()
                #装填菜单
            auto_wear(request,basic,"enterprise_basic_information",'Fillpeopleinfo')
            basic.enterprise = _enterPrise
            basic.submit_type='2'
            basic.application_status=appModel[0]
            basic.save()
            fillModel=request.session['fill']
            appModel=Application_status.objects.get(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
            appModel.app_status="未确认"
            appModel.save()
            return HttpResponseRedirect("/basic/detail/")
        except Exception as e:
            basic_list = Fillpeopleinfo.objects.filter(enterprise = _enterPrise,submit_type='1',application_status=appModel)
            if basic_list:
                basic = basic_list[0]
            else:
                basic = Fillpeopleinfo()
                #装填菜单
            auto_wear(request,basic,"enterprise_basic_information",'Fillpeopleinfo')
            basic.enterprise = _enterPrise
            basic.application_status=appModel[0]
            basic.submit_type='1'
            basic.save()

            info=Enterprise_basic_information.objects.filter(enterprise = _enterPrise,application_status=appModel)
            if info:
                info=info[0]
                if info.submit_type=='1':
                    appModel=Application_status.objects.get(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
                    appModel.app_status="已确认"
                    appModel.save()
            return HttpResponseRedirect("/basic/detail/")
@csrf_exempt
def edit(request):
    _enterPrise = request.session.get('ep')
    parks = _enterPrise.park
    park=Park.objects.filter()
    classifications = Industry_classification_name.objects.all()
    registrations = Registration_type_name.objects.all()
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
    if request.method == "GET":
        try:
            if appModel:
                appModel=appModel[0]
                basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise,application_status=appModel)
            if len(basic_list) > 0:
                basic = basic_list[0]
                business_license_photocopy = basic.business_license_photocopy
                if business_license_photocopy:
                    business_license_photocopy= str(business_license_photocopy)[25:]
                plane_layout = basic.plane_layout
                if plane_layout:
                    plane_layout= str(plane_layout)[25:]   
                geo_center_point = basic.geo_center_point 
                if geo_center_point:
                    basic.geo_center_point = json.loads(geo_center_point)
                return render_to_response('enterprise/basic_information/info/basic_info_edit.html', {  'basic' : basic,"plane_layout":plane_layout,"park":park,"business_license_photocopy":business_license_photocopy,"parks":parks,"classifications":classifications,"registrations":registrations } ,context_instance=RequestContext(request))
            else:
                return render_to_response('enterprise/basic_information/info/basic_info_edit.html',{"parks":_enterPrise.park,"classifications":classifications,"registrations":registrations},context_instance=RequestContext(request))
        except Exception as e:
            return HttpResponse("非法请求\n\n"+e.message)
    if request.method == "POST":
        Enterprise_basic_information.objects.filter(enterprise = _enterPrise,application_status=appModel).delete()
        try:
            key= request.GET['key']
            basic_list=Enterprise_basic_information.objects.filter(enterprise = _enterPrise,submit_type='2',application_status=appModel)
            if basic_list:
                basic = basic_list[0]
            else:
                basic = Enterprise_basic_information()
                #装填菜单
            auto_wear(request,basic,"enterprise_basic_information",'Enterprise_basic_information')
            basic.enterprise = _enterPrise
            basic.submit_type='2'
            basic.application_status=appModel[0]
            basic.save()
            fillModel=request.session['fill']
            appModel=Application_status.objects.get(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
            appModel.app_status="未确认"
            appModel.save()
            return HttpResponseRedirect("/basic/detail/")
        except Exception as e:
            try:
                basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise,submit_type='1',application_status=appModel)
                if basic_list:
                    basic = basic_list[0]
                else:
                    basic = Enterprise_basic_information()
                    #装填菜单
                auto_wear(request,basic,"enterprise_basic_information",'Enterprise_basic_information')
                basic.enterprise = _enterPrise
                basic.application_status=appModel[0]
                basic.submit_type='1'
                basic.save()
                info=Fillpeopleinfo.objects.filter(enterprise = _enterPrise,application_status=appModel)
                if info:
                    info=info[0]
                    if info.submit_type=='1':
                        appModel=Application_status.objects.get(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
                        appModel.app_status="已确认"
                        appModel.save()
                return HttpResponseRedirect("/basic/detail/")
            except Exception as e:
                result = {'error':e.message if '' else (e.__str__()) }
                return HttpResponse(simplejson.dumps(result))
            else:
                result = {'success':'数据修改成功!' }
                return HttpResponse(simplejson.dumps(result))

def detail(request):
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="企业基本信息")
    if appModel:
        appModel=appModel[0]
        basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise,application_status=appModel)
        enter_people=Fillpeopleinfo.objects.filter(enterprise = _enterPrise,application_status=appModel)
    geo_center_point=None
    basic_status=None
    enter_status=None
    basic=None
    if len(basic_list) > 0:
        basic = basic_list[0]
        basic_status=basic.submit_type
        geo_center_point = basic.geo_center_point
    if len(enter_people)>0:
        enter_people=enter_people[0]
        enter_status=enter_people.submit_type
    if geo_center_point:
        basic.geo_center_point = json.loads(geo_center_point)
    return render_to_response('enterprise/basic_information/info/basic_info_detail.html',
                              { 'enter_people':enter_people, 'enter_status':enter_status,'basic' : basic,
                                'basic_status':basic_status,
                                'p': _enterPrise.park } ,
                              context_instance=RequestContext(request))

def preventionDetail(request):
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="环境保护目标信息")
    if appModel:
        appModel=appModel[0]
            # 大气环境保护目标
        gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
        gas = Gas_environment()
        gdetails = []
        if gas_list:
            gas = gas_list[0]
            gdetails =gas.gas_environment_detail_set.all()
       # 水环境保护目标
        water_list = Water_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
        water = Water_environment()
        wdetails = []
        if water_list:
            water = water_list[0]
            wdetails =water.water_environment_detail_set.all()
        #生态环境
        ecological=Ecological.objects.filter(enterprise=_enterPrise,application_status=appModel)
        if ecological:
            eco_status=ecological[0].submit_type
        else:
            eco_status=None
    return render_to_response('enterprise/basic_information/water/basic_WaterGas_detail.html',
                              {"gas":gas,"water":water,"water_est":water.water_exist,"gdetails":gdetails,"wdetails":wdetails,
                               'edetailes':ecological,'status':appModel.app_status,'eco_status':eco_status,
                              'fillModel':fillModel.status
                              },
                              context_instance=RequestContext(request))
@csrf_exempt
def gas_Edit(request):
    """
    大气环境保护目标
    """
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="环境保护目标信息")
    if appModel:
        appModel=appModel[0]
    if request.method == "GET":
        try:
            gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
            gas = Gas_environment();
            details = []
            if gas_list:
                gas = gas_list[0]
                details =gas.gas_environment_detail_set.all()
            return render_to_response('enterprise/basic_information/water/basic_gas_edit.html',{"gas":gas,"details":details},context_instance=RequestContext(request))

        except Exception as e:
            return HttpResponse("非法请求\n\n"+e.message)
    if request.method == "POST":
        try:
            key= request.GET['key']
            try:
                gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
                if gas_list:
                    gas = gas_list[0]
                else:
                    gas = Gas_environment()
                    #装填菜单
                auto_wear(request,gas,"enterprise_basic_information",'Gas_environment')

                gas.enterprise = _enterPrise
                gas.submit_type='2'
                gas.application_status=appModel
                appModel.app_status="未确认"
                appModel.application_status=appModel
                appModel.save()
                # gas.submit_type=
                gas.save()

                gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
                gas = gas_list[0]
                Gas_environment_detail.objects.filter(environment = gas).delete()
                if request.POST["gas_exist"] != "0":
                    list = auto_wear_list(request,Gas_environment_detail,"enterprise_basic_information",'Gas_environment_detail')
                    for a in list:
                        a.environment = gas
                        a.save()
                #details =gas.gas_environment_detail_set.all()
                return HttpResponseRedirect("/basic/prevention/detail/")
            except Exception as e:
                result = {'error':e.message if '' else (e.__str__()) }
                return HttpResponse(simplejson.dumps(result))
            else:
                result = {'success':'数据修改成功!' }
                return HttpResponse(simplejson.dumps(result))
        except Exception as e:
            try:
                gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
                if gas_list:
                    gas = gas_list[0]
                else:
                    gas = Gas_environment()
                    #装填菜单
                auto_wear(request,gas,"enterprise_basic_information",'Gas_environment')

                gas.enterprise = _enterPrise
                gas.submit_type='1'
                gas.application_status=appModel
                gas.save()

                gas_list = Gas_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
                gas = gas_list[0]

                Gas_environment_detail.objects.filter(environment = gas).delete()
                status=request.POST["gas_exist"]
                if request.POST["gas_exist"] != "0":
                    list = auto_wear_list(request,Gas_environment_detail,"enterprise_basic_information",'Gas_environment_detail')
                    for a in list:
                        a.environment = gas
                        a.save()
                #details =gas.gas_environment_detail_set.all()
                return HttpResponseRedirect("/basic/prevention/detail/",status)
            except Exception as e:
                result = {'error':e.message if '' else (e.__str__()) }
                return HttpResponse(simplejson.dumps(result))
            else:
                result = {'success':'数据修改成功!' }
                return HttpResponse(simplejson.dumps(result))
@csrf_exempt
def ecological_Edit(request):
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="环境保护目标信息")
    if appModel:
        appModel=appModel[0]
    if request.method == "GET":
        ecological=Ecological.objects.filter(enterprise=_enterPrise,application_status=appModel)
        if ecological:
            param={'details':ecological}
        else:
            param={'details':None}
        return render_to_response('enterprise/basic_information/water/basic_ecological_edit.html',param,context_instance=RequestContext(request))
    if request.method=="POST":
        Ecological.objects.filter(enterprise=_enterPrise,application_status=appModel).delete()
        name=request.POST.getlist('name')
        gas_code=request.POST.getlist('gas_code')
        gas_distance=request.POST.getlist('gas_distance')
        eco_exist=request.POST.get('eco_exist')
        try:
            key= request.GET['key']
            if eco_exist=='0':
                pass
            else:
                ecosave(len(name),_enterPrise,name,gas_code,application_status=appModel,submitType='2')
            appModel.app_status="未确认"
            appModel.save()
            fillModel.status="no submit"
            fillModel.save()
        except Exception as e:
            if eco_exist=='0':
                pass
            else:
                ecosave(len(name),_enterPrise,name,gas_code,gas_distance,appModel,submitType='1')
            wat=Water_environment.objects.filter(enterprise=_enterPrise,application_status=appModel)
            gas=Gas_environment.objects.filter(enterprise=_enterPrise,application_status=appModel)
            if wat and gas:
                if wat[0].submit_type=='1' and gas[0].submit_type=='1':
                    appModel.app_status="已确认"
                    appModel.save()
        return HttpResponseRedirect("/basic/prevention/detail/")

def ecosave(one_number,_enterPrise,name,gas_code,gas_distance,env,submitType):
    for number in range(one_number):
        ecological=Ecological()
        ecological.name=name[number]
        ecological.gas_code=gas_code[number]
        ecological.gas_distance=gas_distance[number]
        ecological.application_status=env
        ecological.enterprise=_enterPrise
        ecological.submit_type=submitType
        ecological.save()

@csrf_exempt
def water_Edit(request):
    _enterPrise = request.session.get('ep')
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="环境保护目标信息")
    if appModel:
        appModel=appModel[0]
    if request.method == "GET":
        try:
            water_list = Water_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
            water = Water_environment();
            details = []
            if water_list:
                water = water_list[0]
                details =water.water_environment_detail_set.all()
            return render_to_response('enterprise/basic_information/water/basic_water_edit.html',{"water":water,"details":details},context_instance=RequestContext(request))

        except Exception as e:
            return HttpResponse("非法请求\n\n"+e.message)
    if request.method == "POST":
        try:
            water_list = Water_environment.objects.filter(enterprise = _enterPrise,application_status=appModel)
            if water_list:
                water = water_list[0]
            else:
                water = Water_environment()
            auto_wear(request,water,"enterprise_basic_information",'Water_environment')
            try:
                key= request.GET['key']
                water.submit_type='2'
                appModel.app_status="未确认"
                appModel.save()
            except Exception as e:
                water.submit_type='1'
            water.application_status=appModel
            water.enterprise = _enterPrise
            water.save()
            water_list = Water_environment.objects.filter(enterprise = _enterPrise)
            water = water_list[0]
            Water_environment_detail.objects.filter(environment = water).delete()
            if request.POST["water_exist"] != "0":
                list = auto_wear_list(request,Water_environment_detail,"enterprise_basic_information",'Water_environment_detail')
                for a in list:
                    a.environment = water
                    a.save()
            return HttpResponseRedirect("/basic/prevention/detail/")
        except Exception as e:
            result = {'error':e.message if '' else (e.__str__()) }
            return HttpResponse(simplejson.dumps(result))
        else:
            result = {'success':'数据修改成功!' }
            return HttpResponse(simplejson.dumps(result))

def managementDetail(request):
    try:
        return render_to_response('enterprise/basic_env_detail.html')
    except Exception as e:
        return HttpResponse("非法请求\n\n"+e.message)

def managementEdit(request):
    return render_to_response('enterprise/basic_env.html')

def submitLayMenu(request):
    _enterPrise = request.session.get('ep', None)
    fillModel=request.session['fill']
    appModel=Application_status.objects.filter(fill=fillModel,enterprise=_enterPrise,app_name="法律法规遵守情况")
    if appModel:
        appModel=appModel[0]
        env=Environmental_emergencies.objects.filter(enterprise = _enterPrise,application_status=appModel)
        cle=Cleaner_production.objects.filter(enterprise = _enterPrise,application_status=appModel)
        emi=Emissions.objects.filter(enterprise = _enterPrise,application_status=appModel)
        lic=Licenses.objects.filter(enterprise = _enterPrise,application_status=appModel)
        if env and cle and emi and lic:
            if env[0].submit_type=='1' and cle[0].submit_type=='1' and emi[0].submit_type=='1' and lic[0].submit_type=='1':
                appModel.app_status="已确认"
                appModel.save()
            return HttpResponseRedirect("/basic/law/detail/")
        else:
            return HttpResponseRedirect("/basic/law/detail/")
@csrf_exempt
def mapEdit(request):
    _enterPrise = request.session.get('ep', None)
    if not _enterPrise:
        return HttpResponse('用户错误')
    if request.method == 'GET':
        basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise)
        
        if len(basic_list) > 0:
            basic_list = basic_list[0]
        else:
            basic_list = Enterprise_basic_information(enterprise=_enterPrise)
            basic_list.save()
        return render_to_response('enterprise/companyPositionEdit.html', { 'b':basic_list, 'p':_enterPrise.park })

    if request.method == 'POST':
        
        basic_list = Enterprise_basic_information.objects.filter(enterprise = _enterPrise)[0]
        basic_list.geo_center_point = request.POST.get('geo_center_point','')
        basic_list.geo_points = request.POST.get('geo_points','')
        basic_list.geo_extent = request.POST.get('geo_extent','')
        basic_list.save()

        return render_to_response('enterprise/companyPositionEdit.html', { 'b':basic_list, 'p':_enterPrise.park })